<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Request;
use think\Session;

function makeToken(){
    $str = md5(uniqid(md5(microtime(true)), true)); //生成一个不会重复的字符串
    $str = sha1($str); //加密
    return $str;
}


function getAction(){
    $controller = Request::instance()->controller();
    $action = Request::instance()->action();

    // echo $controller;
    // echo $action;

    return $controller .'/'.$action;
}


function getActions($className, $base='think\Controller') {
    $methods = get_class_methods(new $className());
    $baseMethods = get_class_methods(new $base());
    $res = array_diff($methods, $baseMethods);
    return $res;
}

function getControllers($dir) {
    $pathList = glob($dir . '/*.php');
    $res = [];
    foreach($pathList as $key => $value) {
        $res[] = basename($value, '.php');
    }
    return $res;
}

// 用于请求微信接口获取数据
function get_by_curl($url,$post = false){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if($post){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

/**
 * 获取当前登录用户名
 */
function getLoginUsername(){
	$user = Session::get('login_user');
    return $user->name;
}

/**
 * 获取当前登录用户角色
 */
function getLoginUserrole(){
	$user = Session::get('login_user');
    return $user->roleid;
}

/**
*获取控制器
*/
function getActive($nav_controller){
    $controller= Request::instance()->controller();
	if(strtolower($controller)==$nav_controller){
		return 'class="active"';
	}
	return '';
}

function toJson( $data ){
    $result = json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
    return $result;
}

/**
 * $msg 待提示的消息
 * $url 待跳转的链接
 * $icon 这里主要有两个，5和6，代表两种表情（哭和笑）
 * $time 弹出维持时间（单位秒）
 */
function alert($msg='',$url='',$icon='',$time=3){ 
    $str='<script type="text/javascript" src="/thinkadmin/public/static/assets/js/jquery.min.js"></script><script type="text/javascript" src="/thinkadmin/public/static/assets/js/dialog/layer.js"></script>';//加载jquery和layer
    $str.='<script>$(function(){layer.msg("'.$msg.'",{icon:'.$icon.',time:'.($time*1000).'});setTimeout(function(){self.location.href="'.$url.'"},2000)});</script>';//主要方法
    return $str;
}

/**
 * 生成订单号
 * Time: 11:15
 * @param $type 订单类型
 * @return string
 */
function makeOrdersn($type='')
{
    @date_default_timezone_set("PRC");
    //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
    $order_id_main = $type.date('YmdHis') . rand(10000000,99999999);
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for($i=0; $i<$order_id_len; $i++){
        $order_id_sum += (int)(substr($order_id_main,$i,1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
    return $order_id;
}
/**检查邮箱**/
function c_email($email){
  $reg='/^([a-zA-Z0-9]{1,20})(([\_\-\.])?([a-zA-Z0-9]{1,20}))*@([a-zA-Z0-9]{1,20})(([\-\_])?([a-zA-Z0-9]{1,20}))*(\.[a-z]{2,4}){1,2}$/';
  if(preg_match($reg,$email))
    return true;    
  return false;
}
/**
 * 元转分  传入字符串价格 必须-0.00格式
 * @Author      GNLEON
 * @HttpRequest                                                        get|post
 * @Param                                     -
 * @DateTime    2020-10-11
 * @LastTime                                  2020-10-11
 * @copyright   [copyright]
 * @license     [license]
 * @param       [type]                        $price     [description]
 * @return      [type]                                   [description]
 */
function curmoney($price){
    $price_arr = explode(".", $price);
    $price_arr_last = str_split($price_arr[1]);

    return $price_arr[0]*100 + $price_arr_last[0]*10 + $price_arr_last[1]; 
}


/**
 * @param $text 文本
 * @param string $color 文本颜色
 * @param string $backColor 背景颜色
 * @param int $size 字体大小
 * @param int $width 图片宽度
 * @param int $height 图片高度
 * @param string $type 图片类型
 * @return string base64编码图片字符
 */
function createImgBase64($text, $color = '#000000', $backColor = '#ffffff', $size = 30, $width = 300, $height=80, $type = 'jpeg')
{
    $font = ''; //字体文件
    $img = imagecreate($width, $height); //创建图片
    imagecolorallocate($img, hexdec(substr($backColor,1,2)), hexdec(substr($backColor,3,2)), hexdec(substr($backColor,5,2))); //设置背景色
    $penColor = imagecolorallocate($img, hexdec(substr($color,1,2)), hexdec(substr($color,3,2)), hexdec(substr($color,5,2))); //设置文字颜色
    imagettftext($img, $size, 0, ($height-$size)/2, ($height+$size)/2, $penColor, $font, $text); //设置文字大小、显示位置及颜色等
    ob_start();
    switch ($type) {
        case 'jpeg':
            imagejpeg($img);
            break;
        case 'png':
            imagepng($img);
            break;
        case 'gif':
            imagegif($img);
            break;
        case 'bmp':
            imagebmp($img);
            break;
        default :
            imagejpeg($img);
            $type = 'jpeg';
    }
    $contents = ob_get_contents();
    ob_end_clean();
    return "data:image/" . $type . ";base64," . base64_encode($contents);
}



/**
 * 判断是否为合法的身份证号码
 * @param $mobile
 * @return int
 */
function isCreditNo($vStr){
 $vCity = array(
  '11','12','13','14','15','21','22',
  '23','31','32','33','34','35','36',
  '37','41','42','43','44','45','46',
  '50','51','52','53','54','61','62',
  '63','64','65','71','81','82','91'
 );
 if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
 if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
 $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
 $vLength = strlen($vStr);
 if ($vLength == 18) {
  $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
 } else {
  $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
 }
 if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
 if ($vLength == 18) {
  $vSum = 0;
  for ($i = 17 ; $i >= 0 ; $i--) {
   $vSubStr = substr($vStr, 17 - $i, 1);
   $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
  }
  if($vSum % 11 != 1) return false;
 }
 return true;
}